﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Windows;

namespace SuporeSliplampApp.Base
{
    public class SocketService
    {
        public static Socket socket;              
        public static bool isRunning = false;
        static string iP = string.Empty;
        static string port = string.Empty;
        static Task mainTask = null;

        public static void Connect(string ipStr,string portStr)
        {
            if (isRunning) return;
            iP = ipStr;
            port = portStr;
            IPAddress ip = IPAddress.Parse(iP);
            socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            try
            {
                socket.Connect(ip,Convert.ToInt32(port));
                //threadReceive = new Thread(new ThreadStart(Receive));
                isRunning = true;
                Receive();
            }
            catch (Exception ex)
            {
                isRunning = false;
                throw ex;
            }
        }

        private static void Receive()
        {
            mainTask = Task.Run(() => 
            {
                try
                {
                    while (true)
                    {
                        byte[] buff = new byte[1024];
                        int r = socket.Receive(buff, buff.Length, SocketFlags.None);
                    }
                }
                catch 
                {
                    StopService();
                    MessageBox.Show("获取服务器参数失败！");
                }
            });
        }

        public static void StopService() 
        {
            if (isRunning)
            {
                socket.Dispose();
                isRunning = false;
                mainTask.ConfigureAwait(true);
            }
            
        }

    }
}
